package org.ciallo.simplemusicplayer.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.activity.ArtistSongsActivity;
import org.ciallo.simplemusicplayer.adapter.ArtistAdapter;
import org.ciallo.simplemusicplayer.viewmodel.LocalMusicViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.Locale;

/**
 * @author Jukomu
 * @Description: 显示歌手列表的Fragment
 * @Package: org.ciallo.simplemusicplayer.fragment
 * @Project: SimpleMusicPlayer
 * @name: ArtistListFragment
 * @Date: 2025/6/2-22:06
 * @Filename: ArtistListFragment
 */
public class ArtistListFragment extends Fragment {

    private RecyclerView recyclerViewArtists;
    private ArtistAdapter artistAdapter;
    private LocalMusicViewModel localMusicViewModel;
    private TextView tvEmptyList;
    private SwipeRefreshLayout swipeRefreshLayout; // 假设歌手列表也从扫描更新
    private SharedViewModel sharedViewModel;
    private TextView tvArtistSearchLabel; // <--- (可选) 添加搜索结果提示标签

    public ArtistListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 复用 fragment_generic_list.xml 布局
        return inflater.inflate(R.layout.fragment_generic_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

        localMusicViewModel = new ViewModelProvider(requireActivity()).get(LocalMusicViewModel.class);

        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout_generic_list);
        recyclerViewArtists = view.findViewById(R.id.recyclerView_generic);
        tvEmptyList = view.findViewById(R.id.textView_empty_list);
        tvEmptyList.setText("没有找到歌手信息"); // 设置空状态提示

        setupRecyclerView();
        setupSwipeRefreshLayout();
        observeViewModel();
    }

    private void setupRecyclerView() {
        artistAdapter = new ArtistAdapter(artistInfo -> {
            // 点击歌手，跳转到该歌手的歌曲列表页面
            Intent intent = new Intent(getActivity(), ArtistSongsActivity.class);
            // ArtistInfo 中的 artistId 可能来自 MediaStore.Audio.Artists._ID 或 Song.artistIdRoom
            // ArtistSongsActivity 需要能根据这个ID（或直接根据artistName）查询歌曲
            intent.putExtra(ArtistSongsActivity.EXTRA_ARTIST_ID, artistInfo.artistId); // 传递歌手ID
            intent.putExtra(ArtistSongsActivity.EXTRA_ARTIST_NAME, artistInfo.artistName); // 传递歌手名，用于Toolbar标题
            intent.putExtra(ArtistSongsActivity.EXTRA_ARTIST_ALBUM_ART_URI, artistInfo.representativeAlbumArtUri); // 传递封面
            startActivity(intent);
        });
        recyclerViewArtists.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewArtists.setAdapter(artistAdapter);
    }

    private void setupSwipeRefreshLayout() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            Timber.d("ArtistListFragment: Swipe to refresh triggered.");
            // 歌手列表的数据来源于歌曲扫描，所以刷新也是触发歌曲扫描
            localMusicViewModel.startMediaStoreScan();
        });
        if (getContext() != null) { // 设置颜色
            swipeRefreshLayout.setColorSchemeColors(
                    ContextCompat.getColor(getContext(), R.color.md_theme_light_primary),
                    ContextCompat.getColor(getContext(), R.color.md_theme_light_secondary));
        }
    }

    private void observeViewModel() {
        // 1. 观察全局搜索查询词
        sharedViewModel.currentSearchQuery.observe(getViewLifecycleOwner(), query -> {
            Timber.d("ArtistListFragment: Observed global search query: '%s'", query);
            localMusicViewModel.updateSearchQuery(query); // 通知 LocalMusicViewModel 更新其内部查询

            // (可选) 更新此Fragment的搜索结果提示标签
            // if (tvArtistSearchLabel != null) {
            //     if (query != null && !query.trim().isEmpty()) {
            //         tvArtistSearchLabel.setText(String.format(Locale.getDefault(), "“%s”的歌手搜索结果：", query.trim()));
            //         tvArtistSearchLabel.setVisibility(View.VISIBLE);
            //     } else {
            //         tvArtistSearchLabel.setVisibility(View.GONE);
            //     }
            // }
        });

        // 2. 观察扫描状态
        localMusicViewModel.isScanning.observe(getViewLifecycleOwner(), isScanning -> {
            if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(isScanning);
        });

        // 3. 观察最终要显示的歌手列表
        localMusicViewModel.artistsToDisplay.observe(getViewLifecycleOwner(), artists -> {
            Timber.d("ArtistListFragment: artistsToDisplay updated. Count: %d", artists != null ? artists.size() : 0);
            Boolean isLoading = localMusicViewModel.isScanning.getValue();
            String currentQuery = sharedViewModel.currentSearchQuery.getValue();
            boolean searchActive = currentQuery != null && !currentQuery.trim().isEmpty();

            if (artists != null && !artists.isEmpty()) {
                artistAdapter.submitList(new ArrayList<>(artists));
                tvEmptyList.setVisibility(View.GONE);
                recyclerViewArtists.setVisibility(View.VISIBLE);
            } else {
                artistAdapter.submitList(new ArrayList<>());
                recyclerViewArtists.setVisibility(View.GONE);
                if (isLoading == null || !isLoading) {
                    if (searchActive) {
                        tvEmptyList.setText(String.format(Locale.getDefault(), "没有找到与“%s”相关的歌手", currentQuery != null ? currentQuery.trim() : ""));
                    } else {
                        tvEmptyList.setText("没有找到歌手信息");
                    }
                    tvEmptyList.setVisibility(View.VISIBLE);
                } else {
                    tvEmptyList.setVisibility(View.GONE);
                }
            }
        });
    }
}
